package com.zam.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zam.pojo.User;
import com.zam.service.UserService;
import com.zam.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author talent_dog
 * @Date 2023/12/15 16:49
 * @Version 1.0
 */
@Component
public class JwtUtil {
    private static UserService staticUserService;

    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = this.userService;
    }
    //创建
    public static String createJwt(Integer userId,String sign) {
        String jwtoken = JWT.create().withAudience(userId.toString())  //荷载
                .withExpiresAt(DateUtil.offsetHour(new Date(), 3)) //设置3小时过期时间
                .sign(Algorithm.HMAC256(sign)); //设置签名
        return jwtoken;
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
